<?php
/*
 * Created on 2013-4-3
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

//检查并创建目录
function check_and_creat_path($filename)
{
    //检查路径
    $arr_path = explode ( '/', $filename );
    $path = '';
    $cnt = count ($arr_path) - 1;
    if($cnt >= 0 && $arr_path[0] == '')
        chdir('/');
    for($i = 0; $i < $cnt; $i++) 
    {
        if($arr_path[$i] == '') continue;
        $path .= $arr_path [$i] . '/';
        if (! is_dir ( $path ))
            if(!mkdir ( $path ,0755))
                return false;
    }
    
    return true;
}

/**
 * Create a random string
 *
 * @param int $length The length of the random string to create
 * @param string $type The type of random string to create (mixed, chars, digits)
 * @access public
 */

function create_random_string($length, $type = 'mixed') {
	if (!in_array($type, array('mixed', 'chars', 'digits'))) {
		return false;
	}

	$chars_pattern = 'abcdefghijklmnopqrstuvwxyz';
	$mixed_pattern = '1234567890' . $chars_pattern;

	$rand_value = '';

	while (strlen($rand_value) < $length) {
		if ($type == 'digits') {
			$rand_value .= osc_rand(0,9);
		} elseif ($type == 'chars') {
			$rand_value .= substr($chars_pattern, osc_rand(0, 25), 1);
		} else {
			$rand_value .= substr($mixed_pattern, osc_rand(0, 35), 1);
		}
	}

	return $rand_value;
}
 
/**
 * Generate a random number
 *
 * @param int $min The minimum number to return
 * @param int $max The maxmimum number to return
 * @access public
 */

function osc_rand($min = null, $max = null) {
	static $seeded;

	if (!isset($seeded)) {
		if (version_compare(PHP_VERSION, '4.2', '<')) {
			mt_srand((double)microtime()*1000000);
		}

		$seeded = true;
	}

	if (is_numeric($min) && is_numeric($max)) {
		if ($min >= $max) {
			return $min;
		} else {
			return mt_rand($min, $max);
		}
	} else {
		return mt_rand();
	}
}

/**
 * 过滤特殊字符\n,\s
 */
function replaceTagRN($value)
{
	$value = preg_replace('/\s/', ' ', $value);
 	 	
 	return $value;
}

/**
 * 生成图片泛域名
 */
/**
 * 生成图片的泛域名url
 *
 * @param string $rid resource id
 * @param string $attrbute
 * @param boolean $icon_flag rid为空显示默认图片
 * @param boolean $icon 强制转换类型
 */
function image_r($rid, $parameters = '', $icon_flag = false, $icon = false)
{
	if($rid == '' || $rid == null)
	{
		if($icon_flag){
			return '/templates/default/web/images/default_header.jpg';
		}
		else
		{
			return '/templates/default/web/images/default.png';	
		}
	}		
	$str = '';
	$type = '';
	$ridHz = explode('_', $rid);
	
	//强制转换使用普通图片格式显示
	if($icon == true)
	{
		$temp_value = $ridHz[0];
		$temp = substr($temp_value,-1,3);
		if($icon_flag)
		{
			$type = 'icon';
		}
	}
	else 
	{
		$len = count($ridHz);
		if($len == 5){
			$temp = $ridHz[3];		
		}
		elseif($len >= 3)
		{
			$temp_value = $ridHz[0];
			$temp = substr($temp_value,-1,3);	
		}
		else 
		{
			$type = 'icon';
			$temp_value = $ridHz[0];
			$temp = substr($temp_value,-1,3);
		}
	}
	
	for($i=0; $i<3; $i++)
	{
		$str .= ord(substr($temp, $i, 1));
	}
	
	$rs = intval($str) % 32;
	$http_quest = str_replace('http://file', 'http://file'.$rs, TT_SOURSE_URL);	
	if($type == 'icon'){
		$http_quest .= 'rc/geticon?rid=';	
	}
	else
	{
		$http_quest .= 'rc/getpicture?rid=';	
	}	

	return $http_quest . $rid . $parameters;
}

/**
 * 时间转换函数
 */
function format_date($date, $format = 'Y/m/d')
{
	$timestamp = strtotime($date);
	$str = date($format, $timestamp);
	
	return $str;
}

/**
 * time format function
 * @param $timestamp
 * @return string
 */
function fromUnixTimestamp($timestamp)
{
	//default
	if($timestamp == ''){
		return date("m月d日  H:i",time());
	}
	
    //强制转转为长整形
    $date = strtotime($timestamp);
	
	//java timestamp
	if(strlen($date) == 10)
	{
		$now = time();
		$micro = ceil(($now - $date));
		$dt = date("m月d日", $date);
		$y = date("Y", $date);
		$now_y = date("Y", $now);
		
		if($micro < 60)
		{
			$str = '刚刚';
		}
		else if( $micro < 3600)
		{
			$str = (round($micro/60) <= 0 ? 1 : round($micro/60)) . '分钟前';
		}
		else if($y == $now_y)
		{
			if($dt == date("m月d日", $now))
			{
				$str = (round($micro/3600) <= 0 ? 1 : round($micro/3600)) . '小时前';
			}else 
			{
				$str = date("m月d日", $date);
			}
		}
		else
		{
			$str = date("Y年m月d日", $date);
		}

		return $str;
	}
}

/**
 * 翻页组件
 * Enter description here ...
 * @param $total_page
 * @param $page_num
 * @param $cur_page
 * @param $page_url
 * @param $show_num
 */
function get_page_link($total_page, $page_num, $cur_page, $page_url, $show_num = 6)
{
	$string_url = '';

	$num_page = min($cur_page + 5, $total_page);

	if($total_page - $cur_page >= 0 && $total_page - $cur_page < 6)
	{
		$i=5;
		while($i >= 0)
		{
			$num = $total_page-$i;
			if($num > 0)
			{
				if($num == $cur_page)
				{
					$string_url .= '<li><a class="current" href="'.$page_url . '?pageNum='.$page_num.'&curPage='.$num.'">'.$num.'</a></li>';
				}
				else
				{
					$string_url .= '<li><a href="'.$page_url . '?pageNum='.$page_num.'&curPage='.$num.'">'.$num.'</a></li>';
				}
			}
			$i--;
		}
	}
	else
	{
		if($cur_page - 2 >0)
		{
			$string_url .= '<li><a href="'.$page_url . '?pageNum='.$page_num.'&curPage='.($cur_page-2).'">'.($cur_page-2).'</a></li>';
			$string_url .= '<li><a href="'.$page_url . '?pageNum='.$page_num.'&curPage='.($cur_page-1).'">'.($cur_page-1).'</a></li>';
			$string_url .= '<li><a class="current" href="'.$page_url . '?pageNum='.$page_num.'&curPage='.$cur_page.'">'.$cur_page.'</a></li>';
			 
			for ( $i = $cur_page +1; $i <= $num_page-2; $i++ )
			{
				$string_url .= '<li><a href="'.$page_url . '?pageNum='.$page_num.'&curPage='.$i.'">'.$i.'</a></li>';
			}
		}
		else
		{
			$i=5;
			while($i >= 0)
			{
				if(6-$i>0)
				{
					if(6-$i == $cur_page)
					{
						$string_url .= '<li><a class="current" href="'.$page_url . '?pageNum='.$page_num.'&curPage='.$cur_page.'">'.$cur_page.'</a></li>';
					}
					else
					{
						$string_url .= '<li><a href="'.$page_url . '?pageNum='.$page_num.'&curPage='.(6-$i).'">'.(6-$i).'</a></li>';
					}
				}

				$i--;
			}
		}
	}
	
	return $string_url;
}

function format_message_content($content){
	if($content == ''|| $content == 'null'){
		return '';
	}
	
	//过滤特殊字符
	$str = replaceHtmlTag($content);
	
	//处理换行符
	$str = replaceValueRN($str);
	
	$str = str_replace('\n', '<br />', $str);
	
	return $str;
}

//过滤特殊字符
function replaceHtmlTag($value)
{
	$value = str_replace('<script', '&lt;script', $value);
 	//$value = str_replace('>', '&gt;', $value);
 	
 	return $value;
}

//处理换行符
function replaceValueRN($value){
	//匹配多个空行
	$value = preg_replace('/\\\\/', '', $value);
	$value = preg_replace('/\n|\r|\r\n/', '\n', $value);
	$value = preg_replace('/(\\\\n){2,}/', '\n\n', $value);
	
	return $value;
}

/**
 * php获取调用ttcgi接口
 */
function get_ttcgi_curl($action, $params, $sid=''){
	$response = false;
	
	$url = TT_CGI_URL . $action . '?';
	$poststring = http_build_query($params);
	
	if($sid != ''){
		$header[] = 'Tt-Sid:' . $sid;
	}
	$header[] = 'Tt-Channel:100000100';
	//echo $url.$poststring;exit;
	//启动
	$curl_handle = curl_init();
	curl_setopt($curl_handle, CURLOPT_URL, $url);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_handle, CURLOPT_TIMEOUT, 15);
    curl_setopt($curl_handle, CURLOPT_VERBOSE, TRUE);
    curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl_handle, CURLOPT_POST, TRUE);
    curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $poststring);

	$response = curl_exec($curl_handle);
	
	$curl_error = curl_error($curl_handle);
	$curl_errno = curl_errno($curl_handle);
 	$curl_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
 	
 	curl_close($curl_handle);
	if(empty($curl_error))
	{
		if($curl_code <= 100 && $curl_code >= 300)
		{
			log_message('Error', 'url->' . $url . ' params->' . $poststring . ' data->' . $response); 
			$response = false;
		}
	}
	
	if($response !== false){
		$response = json_decode($response, TRUE);
	}
	
	return $response;
}

function extract_uids($data) {
	$uids = array ();
	if (count ( $data ) > 0) {
		foreach ( $data as $row ) {
			if (isset($row['uid']))
				$uids [] = $row['uid'];
		}
	}
	return $uids;
}

function my_sort($a, $b)
{
	 
	if ($a['ctime'] == $b['ctime']) return 0;
	return ($a['ctime'] > $b['ctime']) ? -1 : 1;
}